package beans;

import java.io.Serializable;

import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.SessionScoped;
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.application.Application;

import com.sun.tools.xjc.reader.xmlschema.bindinfo.BIConversion.User;

@ManagedBean
@SessionScoped
public class MBLogin implements Serializable {

	private static final long serialVersionUID = 1L;
private MbHome homeManagedBean = null;
  private User user;

  public MBLogin() {
    Application application = FacesContext.getCurrentInstance().getApplication();
    UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
    int children = root.getChildCount();

    FacesContextFactory factory = (FacesContextFactory) 
        FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);

    for (int i = 0; i < children; i++) {
      System.out.println("O identificador do componente de número " + i
              + " é " + root.getChildren().get(i).getId());
    }

    System.out.println("O número total de views da view raiz é " + children);
  }

  @PostConstruct
  public void loadDefaultValues() {
    homeManagedBean = FacesContext.getCurrentInstance().
            getApplication().evaluateExpressionGet(
            FacesContext.getCurrentInstance(), "#{mbHome}", MbHome.class);

    homeManagedBean.loadSetLists();
  }

  @PreDestroy
  public void saveResources() {
    homeManagedBean.resetSetLists();
  }

  public User getUser() {
    if (user == null) {
      user = new User();
    }
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }

  public String doLogin() {
    return LoginService.doLogin(user);
  }

  public void cleanFields() {
    this.user.setUsername("");
    this.user.setPassword("");
  }
}
